<?php

namespace app\common\service;

use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\order\logic\OrderShipLogic;
use app\order\logic\OrderWhLogic;
use app\order\model\SkuWeightSize;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Config;
use think\facade\Db;

/*
 *  金蚁api:http://qqwy.3wms.com/Pages/DocApi/HomePage.html
 */

class JinyiApiService
{
    protected $url = null;

    public function __construct()
    {
        $this->url = Config('Logisticskey.JY.url');
    }



    /**
     * @param $order
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @desc  生成订单
     */
    public function createOrder($order)
    {
        htmlLog(['order'=>$order],OPERATE_LOG . date('Ym') . '/createOrder/' . date('Ymd') . '.txt');
        $return = [
            'order_id'     => $order['order_id'],
            'shop_id'      => $order['shop_id'],
            'warehouse_id' => $order['warehouse_id'],
            'data'         => '',
            'return0'      => '',
            'return1'      => '',
        ];
        $order['name']        = $order['buyer_name'];
        $order['postal_code'] = $order['post_code'];
        $order['address_detail'] = $order['address'];
        $order['phone_number'] = $order['phone'];
        //获取组装数据
        $JsonData = self::buildJsonData($order);

        $orderDetail_arr = $arr = $OrderDetail = [];
        $skuInfos  = Db::name('order_shopify_list')->where('order_id',$order['order_id'])->value('sku');
        $skuInfos  = explode(',',$skuInfos);
        foreach($skuInfos as $v){
            $orderDetail_arr[] = get_seller_sku($v);
        }

        if(!$orderDetail_arr)  return true;

        //数组整合
        foreach($orderDetail_arr as $v){
            if(isset($v[0]) && is_array($v[0])){
                foreach($v as $value){
                    $arr[] = $value;
                }
            }else{
                    $arr[] = $v;
            }
        }

        foreach($arr as $v){
            $sample_sku = self::get_sample_sku($v['sku']);
            $OrderDetail[] = [
                   'Wt_SKU'   => $sample_sku,
                   'Wt_Number'=> $v['qtyOrdered'],
            ];
        }

        $OrderDetail                 = self::getQtyOrdered($OrderDetail);
        $JsonData["ItemDetailsList"] = $OrderDetail;
        //手动选择金蚁渠道
        $resDeliveryTxt  = self::getDeliveryTxt($order['golden_ant']);
        $JsonData["Wt_DeliveryTxt"]  = $resDeliveryTxt;

        //订单数据推送到金蚁 2024-03-30
        $url = $this->url . Config('Logisticskey.JY.create_order_path');
        $JsonData = (is_array($JsonData)) ? json_encode($JsonData, JSON_UNESCAPED_UNICODE) : $JsonData;
        $JsonDatas['JsonData'] = $JsonData;
        htmlLog(['url'=>$url,'params'=>$JsonDatas,'order_id'=>$order['order_id']],OPERATE_LOG . date('Ym') . '/createOrder/' . date('Ymd') . '.txt');
        $response = HttpUtil::postUrlJY($url, $JsonDatas);
        $result   = json_decode($response, true);
        htmlLog(['response'=>$result,'order_id'=>$order['order_id']],OPERATE_LOG . date('Ym') . '/createOrder/' . date('Ymd') . '.txt');
        //返回结果处理;
        if ($result && $result['Message'] == "操作成功") {
             self::handleSuccessShipping($response,$order,$JsonDatas);
        } else {
             self::handleFailedShipping($response,$order,$return);
        }
        return true;
    }


    /**
     * @desc  构建 JsonData返货参数处理
     * @date  2024-03-30
     * @author luckyXiong
     */
    public function buildJsonData($order=[]){

        $JsonData                             = [];

        $JsonData["Wt_WarehouseTxt"]            = Config('Logisticskey.JY.Wt_WarehouseTxt');
        $JsonData["Wt_IsCOD"]                   = Config('Logisticskey.JY.Wt_IsCOD');
        $JsonData["Wt_PlatformReferenceNumber"] = $order['order_id'];
        //1 存草稿箱  2 待分拣
        $JsonData["Wt_StatusID"]                = Config('Logisticskey.JY.Wt_StatusID');
        //正常情况
        $JsonData["Wt_DeliveryID"]              = Config('Logisticskey.JY.Wt_DeliveryID');
        $JsonData["Wt_DeliveryTxt"]             = Config('Logisticskey.JY.Wt_DeliveryTxt');


        $JsonData["Wt_DeclaredValue"]           = Config('Logisticskey.JY.Wt_DeclaredValue');
        $JsonData["Wt_InsuranceTrue"]           = Config('Logisticskey.JY.Wt_InsuranceTrue');
        $JsonData["ItemDetailsList"]            = [];
        //收货人及公司处理
        $user_name = $this->name_deal($order['name']) ?? $order['name'];
        $JsonData["AddressReceived"]['Wt_Addressee']   = $user_name;
        $JsonData["AddressReceived"]['Wt_CompanyName'] = $user_name;
        //收货人手机号处理(确认去掉(+1)后打开)
        $phone_1 = '';
        if (!empty($order['phone_number'])) {
            $phone_1 = explode('(+1)', $order['phone_number']);
            $phone_1 = $phone_1[1] ?? $phone_1[0];
        }

        $JsonData["AddressReceived"]['Wt_Phone']   = $phone_1;
        $JsonData["AddressReceived"]['Wt_Email']   = $order['buyer_email'];
        $JsonData["AddressReceived"]['Wt_ZipCode'] = $order['postal_code'];
        $JsonData["AddressReceived"]['Wt_Adress']  = $order['address_detail'];

        $JsonData["AddressReceived"]['Wt_CountryTxt']   = '美国';
        //美国州处理
        $state = Db::name('usstate')->where('name_key', $order['state'])->find();
        $state = $state['name_value'] ?? $order['state'];
        $JsonData["AddressReceived"]['Wt_ProvinceTxt'] = $state;
        $JsonData["AddressReceived"]['Wt_CityTxt']     = $order['city'];
        $JsonData["AddressReceived"]['Wt_AreaTxt']     = $order['county']??'';
        // 其他逻辑处理...
        return $JsonData;
    }



    /**
     * @desc   匹配获取可以发货的库存数据
     * @author luckyXiong
     * @date   2024-07-15
     * @title  尾部处理
     */
    public function get_sample_sku($sku=''){
        $sku_info = explode('-',$sku);
        $last     = $sku_info[2]??'';
        if($last=='XL/2XL'){
            $last = 'XL';
        }
        if($last=='3XL/4XL'){
            $last = '3XL';
        }

        if($last=='4XL/5XL'){
            $last = '4XL';
        }

        if($last=='5XL/6XL'){
            $last = '5XL';
        }

        if($last=='6XL/7XL'){
            $last = '6XL';
        }

        if($last=='XS/S'){
            $last = 'S';
        }
        if($last=='M/L'){
            $last = 'M';
        }
        return  $sku_info[0].'-'.$sku_info[1].'-'.$last;
    }


    /**
     * @desc 获取金蚁渠道
     * @date  2024-03-30
     * @author luckyXiong
     */
    public function getDeliveryTxt($golden_ant=''){
        $arr = [
            '1003' => "HWC-TK",
            '2030' => "HWC-DLZ",
            '3030' => "HWC-DLZ-LB",
            '2015' => "TiK-shop",
            '2011' => "HWC-SD",
            '1010' => "HWC-artificial",
            '1009' => "海外仓一6日签",
        ];
        return $arr[$golden_ant]??'';
   }


    public function doInsertOrderShipLog($return=[],$order=[]){
       $updateShip['status'] = 2;
       $updateShip['time']   = time();
       $updateShip['msg']    = $return['msg'];
       $exist_ship =  Db::name('order_ship')->where('order_id', $order['order_id'])->find();
       if($exist_ship){
           Db::name('order_ship')->where('order_id', $order['order_id'])->update($updateShip);
       }else{
            Db::name('order_ship')->insert([
                    'order_id'    =>$order['order_id'],
                    'shop_id'     =>$order['shop_id'],
                    'warehouse_id'=>$order['warehouse_id'],
                    'status'      =>2,
                    'time'        =>time(),
                    'msg'         =>$return['msg'],
                    'type'        =>$order['type'],
            ]);
       }
       OrderShipLogic::insertOrderShipLog($return);
   }

    /**
     * @desc 处理发货成功的情况
     * @date  2024-03-30
     * @author luckyXiong
     */
    private function handleSuccessShipping($response=[],$order=[],$JsonDatas=[])
    {
        $result   = json_decode($response, true);
        $tracking_number   = $result['Data']['Wt_ID']??'';
        $return['code']    = 3;
        $return['msg']     = "回传物流单号";
        $return['return0'] = $response;
        $return['data']    = $tracking_number;
        //有跟踪号代表发货了
        $msg                            = '金蚁自发货，已发货';
        $status                         = 3;
        Db::name('order_shopify_list')->where('order_id', $order['order_id'])->update([
                'ship_status'      =>$status,
                'update_time'      =>date("Y-m-d H:i:s", time()),
                'warehouse_id'     =>$order['warehouse_id'],
                'tracking_number'  =>$tracking_number,
                'msg'              =>$msg,
            ]
        );

        OrderShipLogic::insertOrderShipLog($return);
    }

    /**
     * @desc 处理发货失败的情况
     * @date  2024-03-30
     * @author luckyXiong
     */
    private function handleFailedShipping($response='',$order=[], $return=[])
    {
        $result               = json_decode($response, true);
        $return['code']       = 2;
        $return['msg']        = "错误：" . $result['Message'];
        $return['return0']    = $response;
        $updateShip['ship_status'] = 2;
        $updateShip['update_time'] = date("Y-m-d H:i:s", time());
        $updateShip['msg']    = $return['msg'];
        $updateShip['warehouse_id'] = $order['warehouse_id'];
        Db::name('order_shopify_list')->where('order_id', $order['order_id'])->update($updateShip);
        OrderShipLogic::insertOrderShipLog($return);
    }



    /**
     * @desc 处理发货成功的情况
     * @date  2024-03-30
     * @author luckyXiong
     */
    private function handleSuccessWhShipping($response=[],$order=[],$JsonDatas=[])
    {
        $result            = json_decode($response, true);
        $tracking_number   = $result['Data']['Wt_ID'];
        $return['code']    = 3;
        $return['msg']     = "回传物流单号";
        $return['return0'] = $response;
        $return['data']    = $tracking_number;
        //有跟踪号代表发货了
        $update['tracking_beforehand'] = 3;
        $update['updatetime'] = time();
        $update['tracking_number'] = $tracking_number;
        $update['warehouse_id']    = $order['warehouse_id'];
        $update['msg'] = "回传物流单号";
        Db::name('orderwh')->where('order_id', $order['order_id'])->update($update);
        OrderWhLogic::insertOrderWhLog($return);
    }

    /**
     * @desc 处理发货失败的情况
     * @date  2024-03-30
     * @author luckyXiong
     */
    private function handleFailedWhShipping($order=[], $response=[],$return=[])
    {

        $result            = json_decode($response, true);
        $return['code']    = 2;
        $return['msg']     = "错误：" . $result['Message'];
        $return['warehouse_id']  = $order['warehouse_id'];
        $return['return0'] = $response;
        $update['tracking_beforehand'] = 2;
        $update['updatetime'] = time();
        $update['warehouse_id']    = $order['warehouse_id'];
        $update['msg'] = "错误：" . $result['Message'];
        Db::name('orderwh')->where('order_id', $order['order_id'])->update($update);
        OrderWhLogic::insertOrderWhLog($return);
    }



    /**
     * @desc 手动修改订单发货处理
     * @date  2024-03-30
     * @author luckyXiong
     */
    private function handleUpdateOrder($order=[]){
        $OrderDetail2 = [];
        if (!empty($order['skuinfo'])) {
            $skuinfos = explode(',', $order['skuinfo']);
            foreach ($skuinfos as $ksku => $vsku) {
                $test = [];
                $test["Wt_SKU"] = $vsku;
                $test["Wt_Number"] = 1;
                $OrderDetail2[] = $test;
            }
        }
       return $OrderDetail2;
    }



    /**
     * @param $order
     * @desc 订单回传
     * @date 2024-05-23
     */
    public function update_tracking_number()
    {
        //查询需要回传物流单号的订单 ,通过仓库编码更新
        $where      = [];
        $where[]    = ['ship_status', '=', 3];
        $where[]    = ['warehouse_id', '=', 3];
        $startOfDay = date('Y-m-d 00:00:00', strtotime('-3 days'));
        $endOfDay   = date('Y-m-d 23:59:59');
        $where[]  = ['create_time', 'between', [$startOfDay,$endOfDay]];
        $orders     = Db::name('order_shopify_list')->where($where)->order('create_time asc')->limit(500)->select()->toarray();
        if(!$orders)    return '暂无数据!';
        //通过查询的单号取接口数据循环更新
        foreach ($orders as $order) {
            $order['type']  = 1;
            //推动数据到队列;
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_JINYI_TRACKING_NUMBER_UPDATE_QUEUE,
                $order,
                false
            );
        }
        $num = count($orders);
        return '金蚁处理数据'.$num.'条';
    }

    /**
     * @param $order
     * @desc 网红订单回传
     * @date 2024-05-23
     */
    public function update_tracking_number_wh($order=[])
    {
        $order_id          = $order['order_id']??'';
        if (!empty($order_id)) {
            $where[] = ['order_id', '=', $order_id];
        }
        //查询需要回传物流单号的订单  通过仓库编码更新
        $where[] = ['tracking_beforehand', '=', 3];
        $where[] = ['warehouse_id', '=', 3];
        $where[] = ['tracking_number', '>', 0];
        $orders  = Db::name('orderwh')->where($where)->field('id,order_id,warehouse_id,tracking_number')->order('createtime asc')->select();
        $orders  = objectToArray($orders);
        if(!$orders)    return json(DefaultResponse(201, false, '暂无数据!'));
        //通过查询的单号取接口数据循环更新
        foreach ($orders as $order) {
            $order['type']  = 2;//网红订单
            //推动数据到队列;
            MqTaskPushLogic::mq_task_push(
                    '',
                    MqQueueName::QUEUE_JINYI_TRACKING_NUMBER_UPDATE_QUEUE,
                    $order,
                    false
                );
        }
        return json(DefaultResponse(200, true, '操作成功!'));
    }


    /**
     * @desc    金蚁自发货物流单号回传mq消费方法
     * @date    2024-04-13
     * @author  luckyXiong
     */
    public function tracking_number_update_consumer($order){
        $type                   = $order['type']??'1';
        $shop_id                = $order['shop_id']??'';
        //替换成易境通
        $url =Config('Logisticskey.YiJT.url') . Config('Logisticskey.YiJT.hwc_order');
        $JsonDatas = [
            'token'      => Config('Logisticskey.YiJT.token'),
            'deliver_no' => $order['order_id'],
        ];
        $response = HttpUtil::postUrlYiJT($url,$JsonDatas);
        $result   = json_decode($response, true);
        $result = $result['data'][0] ?? [];
        htmlLog(['params'=>$order,'response'=>$result],OPERATE_LOG . date('Ym') . '/tracking_number_update_consumer/' . date('Ymd') . '.txt');
        $Wt_LogisticsOrderNo  = $result['waybill']??'';
        if($Wt_LogisticsOrderNo){
            self::add_jin_yi_success_log($type,$order['order_id'],$Wt_LogisticsOrderNo,$shop_id,$order['warehouse_id']);
        }else{
            self::add_jin_yi_error_log($type,"物流单号还未生成",$order['order_id'],$Wt_LogisticsOrderNo,$shop_id,$order['warehouse_id']);
        }
        return  true;
    }


    /**
     * @desc  记录金蚁回传单号
     * @date  2024-04-13
     * @author  luckyXiong
     */
    public function add_jin_yi_error_log($type='',$Message='',$order_id='',$Wt_LogisticsOrderNo='',$shop_id='',$warehouse_id=''){
        Db::name('order_shopify_list')->where('order_id', $order_id)->update([
            'ship_status'      => 3,
            'msg'              => $Message,
            'update_time'      =>date("Y-m-d H:i:s", time()),
        ]);
        $return['code']            = 3;
        $return['shop_id']         = $shop_id;
        $return['order_id']        = $order_id;
        $return['warehouse_id']    = $warehouse_id;
        $return['msg']             = $Message;
        $return['data']            = $Wt_LogisticsOrderNo;
        OrderShipLogic::insertOrderShipLog($return);
        return  true;
    }


    /**
     * @desc  记录金蚁回传单号
     * @date  2024-04-13
     * @author  luckyXiong
     */
    public function add_jin_yi_success_log($type='',$order_id='',$Wt_LogisticsOrderNo='',$shop_id='',$warehouse_id=''){
        $old_tracking  = Db::name('order_shopify_list')->where('order_id', $order_id)->find();
        htmlLog(['type'=>$type,'order_id'=>$order_id,'Wt_LogisticsOrderNo'=>$Wt_LogisticsOrderNo,'shop_id'=>$shop_id,'warehouse_id'=>$warehouse_id],OPERATE_LOG . date('Ym') . '/add_jin_yi_success_log/' . date('Ymd') . '.txt');
        if(preg_match("/^9\d{9,}$|^42\d{9,}$/", $Wt_LogisticsOrderNo)){
            $Message         = '金蚁物流单号回传完成';
            $status          = 4;
            $tracking_number = $Wt_LogisticsOrderNo;
            $code            = 4;
            //更新订单主表
            Db::name('order_shopify_list')->where('order_id', $order_id)->update([
                'ship_status'         => $status,
                'tracking_number'     => $tracking_number,
                'msg'                 => $Message,
                'update_time'         =>date("Y-m-d H:i:s", time()),
            ]);

            //update 2025-04-10 获取拆单的物流ID
            $fullment_order_id = Db::name('order_shopify_list')->where('order_id', $order_id)->value('fullment_order_id');
            $fullment_order_id = $fullment_order_id ?:'';
            //数据推送到队列处理,2024-07-12
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_TIK_TRACK_TO_SHOPIFY_QUEUE,
                [
                    'order_id'         =>$order_id,
                    'shop_id'          =>$shop_id,
                    'tracking_number'  =>$tracking_number,
                    'fullment_order_id'=>$fullment_order_id,
                ],
                false
            );
          }else{
            $Message = '物流单号生成中';
            Db::name('order_shopify_list')->where('order_id', $order_id)->update([
                'ship_status'         => 3,
                'tracking_number'     => $old_tracking['tracking_number']??'',
                'msg'                 => '物流单号生成中',
                'update_time'         =>date("Y-m-d H:i:s", time()),
            ]);
            }
            $return['code']   = 3;
            $return['shop_id']= $shop_id;
            $return['order_id'] = $order_id;
            $return['warehouse_id']= $warehouse_id;
            $return['msg']    = $Message;
            $return['data']   = $Wt_LogisticsOrderNo;
            OrderShipLogic::insertOrderShipLog($return);
            return  true;
    }


    /**
     * @desc 金蚁物流单号获取后推送到TIK
     * @Date 2024-4-15
     * @Author  luckyXiong
     */
    public function order_tracking_number_tik_back($info=[]){
        if(!$info)   return  true;
        $field       = 'id,app_key,cipher,app_secret,access_token';
        $account     = Db::name('shops')->where('id',$info['shop_id'])->field($field)->find();
        $base_url    = Config('Logisticskey.TIKTOK.basic_url');
        $path        = Config('Logisticskey.TIKTOK.orders_fulfillment_path');
        $delivery_option_id  = Config('Logisticskey.TIKTOK.delivery_option_id');
        $path = $path . $info['order_id'] . '/packages';
        $sign = $account['app_secret'] . '' . $path . 'app_key' . $account['app_key'] . 'shop_cipher' . $account['cipher'] . 'timestamp' . time() . '{"shipping_provider_id":"' . $delivery_option_id . '","tracking_number":"' . $info['tracking_number'] . '"}' . $account['app_secret'];
        $sign = hash_hmac('sha256', $sign, $account['app_secret']);
        $url = $base_url . $path . "?app_key=" . $account['app_key'] . "&shop_cipher=" . $account['cipher'] . "&sign=" . $sign . "&timestamp=" . time();
        htmlLog(['shipping_provider_id'=>$delivery_option_id,'tracking_number'=>$info['tracking_number']],OPERATE_LOG . date('Ym') . '/order_tracking_number_tik_back/' . date('Ymd') . '.txt');
        return HttpUtil::tikPostUrl($url, ['shipping_provider_id'=>$delivery_option_id,'tracking_number'=>$info['tracking_number']], $account['access_token']);
    }






    //姓名拉丁文处理
    public function name_deal($str = '')
    {
        $rst1 = iconv("utf-8", "ascii//TRANSLIT//IGNORE", $str);
        $result = preg_replace("/[^a-zA-Z0-9\s]/", "", $rst1);
        return $result;
    }

    //生成订单-网红小店
    public function createOrderWh($order)
    {
        $return = [
            'order_id' => $order['order_id'],
            'shop_id'  => $order['shop_id']??'',
            'data'     => '',
            'return0'  => '',
            'return1'  => '',
        ];


        //获取组装数据
        $JsonData  = self::buildJsonData($order);
        if(!$order['skuinfo'])    return true;
        $orderinfo = explode(',', $order['skuinfo']);
        foreach ($orderinfo as  $v) {
            $orderDetail_arr[] = get_seller_sku($v);
        }

        if(!$orderDetail_arr)  return true;

         //数组整合
         foreach($orderDetail_arr as $v){
            if(isset($v[0]) && is_array($v[0])){
                foreach($v as $value){
                    $arr[] = $value;
                }
            }else{
                $arr[] = $v;
            }
        }

         foreach($arr as $v){
            $OrderDetail[] = [
                'Wt_SKU'   => $v['sku'],
                'Wt_Number'=> $v['qtyOrdered'],
            ];
        }

          $JsonData["ItemDetailsList"] = $OrderDetail;


           if (empty($JsonData["ItemDetailsList"])){
            $return['code']     = 2; //SKU问题
            $return['msg']      = "发货失败！SKU未填";
            self::doInsertOrderWhLog($return);
           }

            //先处理重复值
            $OrderDetail2 = $JsonData["ItemDetailsList"];
            $OrderDetail2 =self::getQtyOrdered($OrderDetail2);
            $JsonData["ItemDetailsList"] = $OrderDetail2;
            $JsonData = (is_array($JsonData)) ? json_encode($JsonData, JSON_UNESCAPED_UNICODE) : $JsonData;
            $JsonDatas['JsonData'] = $JsonData;
            $url = $this->url . Config('Logisticskey.JY.create_order_path');
            htmlLog(['url'=>$url,'order_param'=>$order,'params'=>$JsonDatas,'order_id'=>$order['order_id']],OPERATE_LOG . date('Ym') . '/createOrderWh/' . date('Ymd') . '.txt');
            $response = HttpUtil::postUrlJY($url, $JsonDatas);
            $result   = json_decode($response, true);
            //记录日志
            if ($result && $result['Message'] == "操作成功") {
                  self::handleSuccessWhShipping($response,$order,$JsonDatas);
            } else {
                  self::handleFailedWhShipping($order, $response,$return);
            }
           return true;
    }



    /**
     * @desc 数据统计
     * @date 2024-02-22
     */
    public function getQtyOrdered($info)
    {
        $outputArray = [];
        foreach ($info as $item) {
            $sku = $item['Wt_SKU'];
            if (isset($outputArray[$sku])) {
                $outputArray[$sku]['Wt_Number'] += $item['Wt_Number'];
            } else {
                $outputArray[$sku] = $item;
            }
        }
        return array_values($outputArray);
    }

    /**
     * @desc 数据统计
     * @date 2024-03-30
     * @author luckyXiong
     */
    public function doInsertOrderWhLog($return=[],$order=[]){
        $update['status'] = 1;
        $update['time']   = time();
        $update['msg']    = $return['msg'];
        Db::name('orderwh')->where('order_id', $order['order_id'])->update($update);
        OrderWhLogic::insertOrderWhLog($return);
    }


}
